package com.hefan.live.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.constant.RedisKeyConstant;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.*;
import com.hefan.live.config.LiveConfigCenter;
import com.hefan.live.itf.LivingRedisOptService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 直播间REDIS操作
 * 
 * @author kevin_zhang
 *
 */
@Component("livingRedisOptService")
public class LivingRedisOptServiceImpl implements LivingRedisOptService {
	public Logger logger = LoggerFactory.getLogger(LivingRedisOptServiceImpl.class);
	@Resource
	JedisService jedisService;

	@Resource
	private LiveConfigCenter liveConfigCenter;

	/**
	 * 增加指定主播的直播信息
	 */
	@Override
	public long addLivingInfo_Hash(String anchId, String livingInfo) {
		long result = 0l;
		try {
			logger.info("addLivingInfo_Hash  anchId：" + anchId + " livingInfo：" + livingInfo);
			result = jedisService.hsetStr(GlobalConstants.LIVING_ROOM_HASH_KEY, anchId, livingInfo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 删除指定主播的直播信息
	 */
	@Override
	public long delLivingInfo_Hash(String anchId) {
		long result = -1;
		try {
			logger.info("delLivingInfo_Hash  anchId：" + anchId);
			result = jedisService.hdel(GlobalConstants.LIVING_ROOM_HASH_KEY, anchId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 查询指定主播是否正在直播中
	 */
	@Override
	public boolean isExistsLivingInfo_Hash(String anchId) {
		boolean result = false;
		try {
			logger.info("isExistsLivingInfo_Hash  anchId：" + anchId);
			result = jedisService.hexists(GlobalConstants.LIVING_ROOM_HASH_KEY, anchId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("isExistsLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 查询指定主播的直播信息
	 */
	@Override
	public String getLivingInfo_Hash(String anchId) {
		String result = null;
		try {
			logger.info("getLivingInfo_Hash  anchId：" + anchId);
			result = jedisService.hgetStr(GlobalConstants.LIVING_ROOM_HASH_KEY, anchId);
			logger.info("getLivingInfo_Hash  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 查询所有正在直播的直播信息
	 */
	@Override
	public Map<String, String> getAllLivingInfo_Hash() {
		Map<String, String> result = new HashMap<>();
		try {
			result = jedisService.hgetAllStr(GlobalConstants.LIVING_ROOM_HASH_KEY);
			logger.info("getAllLivingInfo_Hash  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getAllLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 增加用户进入直播间的Check信息
	 */
	@Override
	public long addUserEnterLivingInfo_Hash(String userId, String valueCheck) {
		long result = 0l;
		try {
			logger.info("addUserEnterLivingInfo_Hash  userId：" + userId + " valueCheck：" + valueCheck);
			result = jedisService.hset(GlobalConstants.LIVING_CHECK_ENTER_HASH_KEY, userId, valueCheck, 0);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addUserEnterLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 删除用户进入直播间的Check信息
	 */
	@Override
	public long delUserEnterLivingInfo_Hash(String userId) {
		long result = 0l;
		try {
			logger.info("delUserEnterLivingInfo_Hash  userId：" + userId);
			result = jedisService.hdel(GlobalConstants.LIVING_CHECK_ENTER_HASH_KEY, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delUserEnterLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 查询用户是否有进入直播间的Check信息
	 */
	@Override
	public boolean isExistsUserEnterLivingInfo_Hash(String userId) {
		boolean result = false;
		try {
			logger.info("isExistsUserEnterLivingInfo_Hash  userId：" + userId);
			result = jedisService.hexists(GlobalConstants.LIVING_CHECK_ENTER_HASH_KEY, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("isExistsUserEnterLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 查询用户进入直播间的Check信息
	 */
	@Override
	public String getUserEnterLivingInfo_Hash(String userId) {
		String result = null;
		try {
			logger.info("getUserEnterLivingInfo_Hash  userId：" + userId);
			result = (String) jedisService.hget(GlobalConstants.LIVING_CHECK_ENTER_HASH_KEY, userId);
			logger.info("getUserEnterLivingInfo_Hash  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getUserEnterLivingInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 向直播间添加进入的用户信息
	 */
	@Override
	public long addLivingUserInfo_Hash(String anchId, String userId, String livingPersonStr) {
		long result = 0l;
		try {
			logger.info("addLivingUserInfo_Hash  livingPersonStr：" + livingPersonStr);
			String key = GlobalConstants.LIVING_ROOM_USER_HASH_KEY + anchId;
			logger.info("addLivingUserInfo_Hash  key：" + key);
			result = jedisService.hset(key, userId, livingPersonStr, 0);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingUserInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 删除直播间中指定的用户信息
	 */
	@Override
	public long delLivingUserInfo_Hash(String anchId, String userId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_HASH_KEY + anchId;
			logger.info("delLivingUserInfo_Hash  key：" + key);
			result = jedisService.hdel(key, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delLivingUserInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 删除直播间中所有的用户信息
	 */
	@Override
	public long delAllLivingUserInfo_Hash(String anchId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_HASH_KEY + anchId;
			logger.info("delAllLivingUserInfo_Hash  key：" + key);
			result = jedisService.del(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delAllLivingUserInfo_Hash  error", e);
		}
		return result;
	}

	/**
	 * 获取指定直播间的用户信息
	 */
	@Override
	public String getLivingUserInfo_Hash(String anchId, String userId) {
		String result = null;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_HASH_KEY + anchId;
			logger.info("getLivingUserInfo_Hash  key：" + key);
			result =  (String) jedisService.hget(key, userId);
			logger.info("getLivingUserInfo_Hash  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingUserInfo_Hash  error", e);
		}
		return result;
	}
	
	/**
	 * 向直播间添加进入的用户信息(排序)
	 */
	@Override
	public long addLivingUserInfo_SortedSet(String anchId, double sortScore, String userId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			logger.info("addLivingUserInfo_SortedSet  key：" + key);
			result = jedisService.zadd(key, sortScore, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingUserInfo_SortedSet  error", e);
		}
		return result;
	}

	/**
	 * 查询用户是否在直播间
	 */
	@Override
	public Long isInRoom(String anchId, String userId) {
		Long result = null;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			result = jedisService.zrank(key, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("isInRoom error" ,e);
		}
		return  result;
	}

	/**
	 * 删除直播间中指定的用户信息(排序)
	 */
	@Override
	public long delLivingUserInfo_SortedSet(String anchId, String userId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			logger.info("delLivingUserInfo_SortedSet  key：" + key);
			result = jedisService.zrem(key, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delLivingUserInfo_SortedSet  error", e);
		}
		return result;
	}

	/**
	 * 删除直播间中指定的用户信息(排序)
	 */
	@Override
	public long delAllLivingUserInfo_SortedSet(String anchId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			logger.info("delAllLivingUserInfo_SortedSet  key：" + key);
			result = jedisService.del(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delAllLivingUserInfo_SortedSet  error", e);
		}
		return result;
	}

	/**
	 * 获取指定主播直播间观看人数(排序)
	 */
	@Override
	public long getLivingUserCount_SortedSet(String anchId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			logger.info("getLivingUserCount_SortedSet  key：" + key);
			result = jedisService.zcard(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingUserCount_SortedSet  error", e);
		}
		return result;
	}

	/**
	 * 分页获取指定主播直播间用户列表(排序)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List getLivingUserList_SortedSet(String anchId, int pageNum, int pageSize) {
		List result = new ArrayList<>();
		try {
			logger.info(
					"getLivingUserList_SortedSet  anchId：" + anchId + " pageNum：" + pageNum + " pageSize：" + pageSize);
			String key = GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			logger.info("getLivingUserList_SortedSet  key：" + key);
			List userIds = jedisService.zrevrange(key, (pageNum - 1) * pageSize, pageNum * pageSize - 1);
			if (null != userIds && userIds.size() > 0) {
				for (Object item : userIds) {
					try {
						String userId = (String) item;
						String livePersonStr = getLivingUserInfo_Hash(anchId, userId);
						if (StringUtils.isNotBlank(livePersonStr)) {
							LiveRoomPersonVo vo = JSON.parseObject(livePersonStr, LiveRoomPersonVo.class);
							logger.info("getLivingUserList_SortedSet  获取直播间用户信息:" + vo);
							result.add(vo);
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.error("getLivingUserList_SortedSet  解析错误", e);
					}
				}
			}
			logger.info("getLivingUserList_SortedSet  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingUserList_SortedSet  error", e);
		}
		return result;
	}

	/**
	 * 获取直播间全部观众的ID
     */
	@Override
	public List getAllUserIdInRoom(String anchId) {
		List result = new ArrayList<>();
		try {
			String key =  GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId;
			result = jedisService.zrevrange(key,0,999999999);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getAllUserIdInRoom error");
		}
		return result;
	}

	/**
	 * 向指定主播的直播间添加机器人
	 */
	@Override
	public long addLivingRobot(String anchId, String userId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId;
			logger.info("addLivingRobot  key：" + key);
			result = jedisService.rpush(key, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingRobot  error", e);
		}
		return result;
	}

	/**
	 * 移除一个直播间机器人（后归还全局）
	 */
	@Override
	public String removeLivingRobot(String anchId) {
		String result = null;
		try {
			String key = GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId;
			logger.info("removeLivingRobot  key：" + key);
			result = (String) jedisService.lpop(key);
			logger.info("removeLivingRobot  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("removeLivingRobot  error", e);
		}
		return result;
	}

	/**
	 * 取指定主播直播间所有机器人ID
	 */
	@Override
	public List getLivingRoomRobotList(String anchId) {
		List result = new ArrayList<>();
		try {
			String key = GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId;
			logger.info("getLivingRoomRobotList  key：" + key);
			result = jedisService.lrange(key, 0, -1);
			logger.info("getLivingRoomRobotList  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingRoomRobotList  error", e);
		}
		return result;
	}

	/**
	 * 取指定主播直播间机器人个数
	 */
	@Override
	public long getLivingRobotCount(String anchId) {
		long result = 0l;
		try {
			result = jedisService.llen(GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingRobotCount  error", e);
		}
		return result;
	}

	/**
	 * 取redis中所有机器人的数量
	 */
	@Override
	public long getLivingRobotCount() {
		long result = 0l;
		try {
			logger.info("getLivingRobotCount");
			result = jedisService.llen(GlobalConstants.LIVING_ROBOT_LIST_KEY );
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingRobotCount  error", e);
		}
		return result;
	}

	/**
	 * 向全局机器人列表中添加机器人
	 */
	@Override
	public long addWholeRobot(String userId,String robotStr) {
		long result = -1l;
		try {
			logger.info("addWholeRobot  robotStr：" + robotStr);
			String idKey = GlobalConstants.LIVING_ROBOT_LIST_KEY;
			String infoKey = GlobalConstants.LIVING_ROBOT_HASHSET_KEY;
			if(jedisService.rpush(idKey, userId) > 0){
				result = jedisService.hset(infoKey, userId, robotStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addWholeRobot  error", e);
		}
		return result;
	}

	/**
	 * 删除机器人信息的IDlist和infoHash
	 */
	@Override
	public void clearRobot() {
		try {
			String idKey = GlobalConstants.LIVING_ROBOT_LIST_KEY;
			String infoKey = GlobalConstants.LIVING_ROBOT_HASHSET_KEY;
			jedisService.del(idKey);
			jedisService.del(infoKey);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("clearRobot ,error");
		}
	}

	/**
	 * 查询缓存中机器人信息数量
	 */
	@Override
	public long getWholeRobotCount() {
		long result = -1l;
		try {
			String key = GlobalConstants.LIVING_ROBOT_HASHSET_KEY;
			result = jedisService.hlen(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addWholeRobot  error", e);
		}
		return result;
	}
	/**
	 * 查询缓存中机器人信息数量
	 */
	@Override
	public long getWholeRobotIdCount() {
		long result = -1l;
		try {
			String key = GlobalConstants.LIVING_ROBOT_LIST_KEY;
			result = jedisService.llen(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getWholeRobotIdCount  error", e);
		}
		return result;
	}

	/**
	 * 取全局机器人中的一个ID
	 */
	@Override
	public String getRobotIdInAll() {
		String result = null;
		try {
			result = (String) jedisService.lpop(GlobalConstants.LIVING_ROBOT_LIST_KEY);
			logger.info("getRobotIdInAll  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getRobotIdInAll  error", e);
		}
		return result;
	}

	/**
	 * 归还全局机器人中的一个ID
	 */
	@Override
	public long returnRobotIdToAll(String userId) {
		long result = 0;
		String key = GlobalConstants.LIVING_ROBOT_LIST_KEY;
		try {
			jedisService.lrem(key, 0, userId);
			result = jedisService.rpush(key, userId);
			logger.info("returnRobotIdToAll  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("returnRobotIdToAll  error", e);
		}
		return result;
	}

	/**
	 * 关播时批量归还机器人ID
	 * @param anchId
	 * @param listRobotIds
	 */
	@Override
	public void returnRobotIdsToAll(String anchId, List listRobotIds){
		String userId;
		String key = GlobalConstants.LIVING_ROBOT_LIST_KEY;
		try {
			for (Object item : listRobotIds) {
				try {
					userId = (String) item;
					if (StringUtils.isNotBlank(userId)) {
						jedisService.lrem(key, 0, userId);
						logger.info("归还机器人，主播：{}，机器人：{}，redis返回：{}", anchId, userId, jedisService.rpush(key, userId));
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("归还全局机器人  error");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("returnRobotIdsToAll  error");
		}
	}

	/**
	 * 获取机器人在缓存中的信息
	 * @param userId
	 * @return json for robotinfo
     */
	@Override
	public String getRobotInfoInAll(String userId) {
		String result = "";
		try {
			result = jedisService.hgetStr(GlobalConstants.LIVING_ROBOT_HASHSET_KEY, userId);
			logger.info("getRobotInfoInAll  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getRobotInfoInAll  error", e);
		}
		return result;
	}

	/**
	 * 设置机器人所在位置（主播ID）
	 * @param userId
	 * @return anchId
	 */
	@Override
	public long setRobotLocation(String userId, String anchId) {
		long result = 0;
		try {
			String key = GlobalConstants.LIVING_ROBOT_LOCATION_HASHSET;
			result = jedisService.hsetStr(key, userId, anchId);
			logger.info("setRobotLocation  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("setRobotLocation  error", e);
		}
		return result;
	}

	/**
	 * 获取机器人所在位置（主播ID）
	 * @param userId
	 * @return anchId
	 */
	@Override
	public String getRobotLocation(String userId) {
		String result = null;
		try {
			String key = GlobalConstants.LIVING_ROBOT_LOCATION_HASHSET;
			result = jedisService.hgetStr(key, userId);
			logger.info("getRobotLocation  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getRobotLocation  error", e);
		}
		return result;
	}

	/**
	 * 移除所有全局机器人
	 */
	@Override
	public long removeAllWholeRobot_List() {
		long result = 0l;
		try {
			result = jedisService.del(GlobalConstants.LIVING_ROBOT_LIST_KEY);
			logger.info("removeAllLivingRobot_List  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("removeAllLivingRobot_List  error", e);
		}
		return result;
	}

	/**
	 * 移除所有直播间机器人
	 */
	@Override
	public long removeAllRoomRobot(String anchId) {
		long result = 0l;
		try {
			result = jedisService.del(GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId);
			logger.info("removeAllRoomRobot  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("removeAllRoomRobot  error", e);
		}
		return result;
	}

	/**
	 * 初始化直播间第一页用户列表信息
	 */
	@Override
	public String initLivingHomePageUserListInfo(String liveUuid, String valueStr) {
		String result = null;
		try {
			logger.info("initLivingHomePageUserListInfo  valueStr：" + valueStr);
			String key = GlobalConstants.LIVE_ROOM_HOME_PAGE_USER_LIST_KEY + "_" + liveUuid;
			logger.info("initLivingHomePageUserListInfo  key：" + key);
			result = jedisService.setexStr(key, valueStr, GlobalConstants.LIVE_ROOM_HOME_PAGE_USER_LIST_CACHE_TIME);
			logger.info("initLivingHomePageUserListInfo  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("initLivingHomePageUserListInfo  error", e);
		}
		return result;
	}

	/**
	 * 增加直播间第一页用户列表信息
	 */
	@Override
	public void addLivingHomePageUserListInfo(String liveUuid, String valueStr) {
		try {
			logger.info("addLivingHomePageUserListInfo  valueStr：" + valueStr);
			String key = GlobalConstants.LIVE_ROOM_HOME_PAGE_USER_LIST_KEY + "_" + liveUuid;
			logger.info("addLivingHomePageUserListInfo  key：" + key);
			jedisService.setStr(key, valueStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingHomePageUserListInfo  error", e);
		}
	}

	/**
	 * 查询直播间第一页用户列表信息
	 */
	@Override
	public String getLivingHomePageUserListInfo(String liveUuid) {
		String result = null;
		try {
			String key = GlobalConstants.LIVE_ROOM_HOME_PAGE_USER_LIST_KEY + "_" + liveUuid;
			logger.info("getLivingHomePageUserListInfo  key：" + key);
			result = jedisService.getStr(key);
			logger.info("getLivingHomePageUserListInfo  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingHomePageUserListInfo  error", e);
		}
		return result;
	}

	/**
	 * 初始化直播间心跳
	 */
	@Override
	public String initLivingHeartBeatInfo(String liveUuid, String valueStr) {
		String result = null;
		try {
			logger.info("initLivingHeartBeatInfo  valueStr：" + valueStr);
			String key = GlobalConstants.LIVE_ROOM_HEART_BEAT_KEY + liveUuid;
			logger.info("initLivingHeartBeatInfo  key：" + key);
			result = jedisService.setexStr(key, valueStr, GlobalConstants.LIVE_ROOM_HEART_BEAT_CACHE_TIME);
			logger.info("initLivingHeartBeatInfo  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("initLivingHeartBeatInfo  error", e);
		}
		return result;
	}

	/**
	 * 增加直播间心跳
	 */
	@Override
	public void addLivingHeartBeatInfo(String liveUuid, String valueStr) {
		try {
			logger.info("addLivingHeartBeatInfo  valueStr：" + valueStr);
			String key = GlobalConstants.LIVE_ROOM_HEART_BEAT_KEY + liveUuid;
			logger.info("addLivingHeartBeatInfo  key：" + key);
			jedisService.setStr(key, valueStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingHeartBeatInfo  error", e);
		}
	}

	/**
	 * 查询直播间心跳信息
	 */
	@Override
	public String getLivingHeartBeatInfo(String liveUuid) {
		String result = null;
		try {
			String key = GlobalConstants.LIVE_ROOM_HEART_BEAT_KEY + liveUuid;
			logger.info("getLivingHeartBeatInfo  key：" + key);
			result = jedisService.getStr(key);
			logger.info("getLivingHeartBeatInfo  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingHeartBeatInfo  error", e);
		}
		return result;
	}

	/**
	 * 初始化直播间观看人次
	 */
	@Override
	public void initLivingWatchNum(String liveUuid, int watchNum) {
		try {
			logger.info("initLivingWatchNum  liveUuid：" + liveUuid);
			String key = GlobalConstants.LIVING_WATCH_NUM_KEY + liveUuid;
			logger.info("initLivingWatchNum  key：" + key);
			jedisService.incrBy(key, watchNum);
			jedisService.expire(key, GlobalConstants.LIVING_WATCH_NUM_CACHE_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("initLivingWatchNum  error", e);
		}
	}

	/**
	 * 增加直播间观看人次
	 */
	@Override
	public long addLivingWatchNum(String liveUuid, int watchNum) {
		long result = 0l;
		try {
			logger.info("addLivingWatchNum  liveUuid：" + liveUuid);
			String key = GlobalConstants.LIVING_WATCH_NUM_KEY + liveUuid;
			logger.info("addLivingWatchNum  key：" + key);
			result = jedisService.incrBy(key, watchNum);
			logger.info("addLivingWatchNum  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingWatchNum  error", e);
		}
		return result;
	}

	/**
	 * 获取直播间观看人次
	 */
	@Override
	public String getLivingWatchNum(String liveUuid) {
		String result = null;
		try {
			logger.info("getLivingWatchNum  liveUuid：" + liveUuid);
			String key = GlobalConstants.LIVING_WATCH_NUM_KEY + liveUuid;
			logger.info("getLivingWatchNum  key：" + key);
			result = jedisService.getStr(key);
			logger.info("getLivingWatchNum  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingWatchNum  error", e);
		}
		return result;
	}
	
	/**
	 * 存直播间踢出信息
	 */
	@Override
	public String setLivingForbiddenEnter(String liveUuid, RoomOuter roomOuter) {
		String result = null;
		try {
			logger.info("setLivingForbiddenEnter  liveUuid：" + liveUuid);
			String key = GlobalConstants.IS_FORBIDDEN_ENTER_KEY + liveUuid + "_" + roomOuter.getUserId();
			logger.info("setLivingForbiddenEnter  key：" + key);
			result = jedisService.setexStr(key, JSON.toJSONString(roomOuter), GlobalConstants.IS_FORBIDDEN_ENTER_CACHE_TIME);
			logger.info("setLivingForbiddenEnter  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("setLivingForbiddenEnter  error", e);
		}
		return result;
	}

	/**
	 * 获取直播间踢出信息
	 */
	@Override
	public String getLivingForbiddenEnter(String liveUuid, String userId) {
		String result = null;
		try {
			logger.info("getLivingForbiddenEnter  liveUuid：" + liveUuid);
			String key = GlobalConstants.IS_FORBIDDEN_ENTER_KEY + liveUuid + "_" + userId;
			logger.info("getLivingForbiddenEnter  key：" + key);
			result = jedisService.getStr(key);
			logger.info("getLivingForbiddenEnter  result：" + result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("getLivingForbiddenEnter  error", e);
		}
		return result;
	}

	/**
	 * 存储live_log live_room数据到redis
	 */
	public boolean addLiveLogData(LiveRoom liveRoom, LiveLog liveLog, LivingRoomInfoVo lriVo){
		String liveLogCache = "";
		String liveRoomCache = "";
		String livingRoomInfoCache = "";
		logger.info("addLiveLogData  anchId：" + liveLog.getUserId());
		try {
			String key = GlobalConstants.LIVE_LOG_DATA + liveLog.getUserId();
			liveLogCache = jedisService.setexStr(key, JSON.toJSONString(liveLog), GlobalConstants.LIVE_LOG_DATA_CACHE_TIME);
			key = GlobalConstants.LIVE_ROOM_DATA + liveLog.getUserId();
			liveRoomCache = jedisService.setexStr(key, JSON.toJSONString(liveRoom), GlobalConstants.LIVE_ROOM_DATA_CACHE_TIME);
			key = GlobalConstants.LIVE_INFO_DATA + liveLog.getUserId();
			livingRoomInfoCache = jedisService.setexStr(key, JSON.toJSONString(lriVo), GlobalConstants.LIVE_INFO_DATA_CACHE_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLiveLogData  error", e);
		}
		if (liveLogCache.equals("OK") && liveRoomCache.equals("OK") && livingRoomInfoCache.equals("OK")){
			logger.info("addLiveLogData insert redis success  anchId：" + liveLog.getUserId());
			return true;
		}else {
			logger.info("addLiveLogData insert redis unsuccess  anchId：" + liveLog.getUserId());
			return false;
		}
	}

	/**
	 * 取liveLog缓存数据
	 */
	@Override
	public LiveLog getLiveLogData(String userId){
		LiveLog liveLog = null;
		logger.info("getLiveLogData  anchId：" + userId );
		try {
			String key = GlobalConstants.LIVE_LOG_DATA + userId;
			liveLog  = JSON.parseObject(jedisService.getStr(key),LiveLog.class);
		} catch (Exception e) {
			logger.info("getLiveLogData  error：" + userId );
		}
		return liveLog;
	}

	/**
	 * 取liveRoom缓存数据
	 */
	@Override
	public LiveRoom getLiveRoomData(String userId){
		LiveRoom liveRoom = null;
		logger.info("getLiveRoomData  anchId：" + userId );
		try {
			String key = GlobalConstants.LIVE_ROOM_DATA + userId;
			liveRoom  = JSON.parseObject(jedisService.getStr(key),LiveRoom.class);
		} catch (Exception e) {
			logger.info("getLiveRoomData  error：" + userId );
		}
		return liveRoom;
	}

	/**
	 * 取liveInfo缓存数据
	 */
	@Override
	public LivingRoomInfoVo getLivingRoomInfoVoData(String userId){
		LivingRoomInfoVo livingRoomInfoVo = null;
		logger.info("getLivingRoomInfoVoData  anchId：" + userId );
		try {
			String key = GlobalConstants.LIVE_INFO_DATA + userId;
			livingRoomInfoVo  = JSON.parseObject(jedisService.getStr(key),LivingRoomInfoVo.class);
		} catch (Exception e) {
			logger.info("getLivingRoomInfoVoData  error：" + userId );
		}
		return livingRoomInfoVo;
	}

	/**
	 * 清除liveLog、liveRoom、liveInfo缓存数据
	 */
	@Override
	public void delLiveCacheData(String userId) {
		try {
			jedisService.del(GlobalConstants.LIVE_LOG_DATA + userId);
			jedisService.del(GlobalConstants.LIVE_ROOM_DATA + userId);
			jedisService.del(GlobalConstants.LIVE_INFO_DATA + userId);
		} catch (Exception e) {
			logger.info("delLiveCacheData error：" + userId );
		}
	}

	/**
	 * 获取直播token
	 */
	@Override
	public String getLiveToken(String userId) {
		String token = "";
		try {
			token = jedisService.getStr(GlobalConstants.LIVE_TOKEN + userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("开播获取token失败",e);
		}
		return token;
	}

	/**
	 * 设置直播token
	 */
	@Override
	public String setLiveToken(String userId, String token){
		String result = "";
		try {
			result = jedisService.setexStr(GlobalConstants.LIVE_TOKEN + userId, token, GlobalConstants.LIVE_TOKEN_CACHE_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("删除开播token失败",e );
		}
		return result;
	}

	/**
	 * 清除开播token
     */
	@Override
	public long delLiveToken(String userId) {
		long l = 0l;
		try {
			l = jedisService.del(GlobalConstants.LIVE_TOKEN + userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("删除开播token失败",e );
		}
		return l;
	}

	/**
	 * 设置禁言用户
     */
	@Override
	public String addShutUpUser(RoomShutup roomShutup, String liveUuid, String userId) {
		String result = "";
		String key = GlobalConstants.ROOM_SHUTUP_KEY + liveUuid + "_" + userId;
		try {
			result = jedisService.setexStr(key,JSON.toJSONString(roomShutup),GlobalConstants.ROOM_SHUTUP_KEY_CACHE_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("禁言存储redis失败"+roomShutup.getUserId());
		}
		return result;
	}

	/**
	 * 获取禁言用户
	 */
	@Override
	public String getShutUpUser(String liveUuid, String userId){
		String result = "";
		String key = GlobalConstants.ROOM_SHUTUP_KEY + liveUuid + "_" + userId;
		try {
			result = jedisService.getStr(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取禁言信息redis失败"+ userId);
		}
		return result;
	}

	/**
	 * 用户是否被禁言
	 */
	@Override
	public boolean isShutUpUser(String liveUuid, String userId){
		boolean result = false;
		String key = GlobalConstants.ROOM_SHUTUP_KEY + liveUuid + "_" + userId;
		try {
			result = jedisService.isExist(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取禁言信息redis失败"+ userId);
		}
		return result;
	}

	/**
	 * 设置新进入直播间时间
	 */
	@Override
	public String addLastJoinTime(String anchId) {
		String result = "";
		String key = GlobalConstants.JOIN_ROOM_LAST_TIME + anchId;
		try {
			result = jedisService.setexStr(key,String.valueOf(System.currentTimeMillis()),GlobalConstants.JOIN_ROOM_LAST_TIME_CACHE_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("更新最新进入直播间时间redis缓存失败" + anchId );
		}
		return result;
	}

	/**
	 * 获取最新进入直播间时间
	 */
	@Override
	public String getLastJoinTime(String anchId){
		String result = "";
		String key = GlobalConstants.JOIN_ROOM_LAST_TIME + anchId;
		try {
			result = jedisService.getStr(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取最新进入直播间时间redis缓存失败" + anchId );
		}
		return result;
	}

  /**
   * 获取本次直播间收入
   */
  @Override
  public long getTicketCountByUuid(String liveUuid){
    long result = 0l;
    String key = String.format(RedisKeyConstant.ANCHOR_LIVE_INCOME, liveUuid);
    try {
      result = jedisService.incrBy(key, 0);
    } catch (Exception e) {
      e.printStackTrace();
      logger.info("获取本次直播收入reids失败"+liveUuid);
    }
    return result;
  }

  /**
   * 清除本次直播收入缓存--设置两小时缓存失效时间
   */
  @Override
  public void delTicketCountByUuid(String liveUuid){
    String key = String.format(RedisKeyConstant.ANCHOR_LIVE_INCOME, liveUuid);
    try {
      jedisService.expire(key, 60 * 60 );
    } catch (Exception e) {
      e.printStackTrace();
      logger.info("直播收入缓存清理失败,liveUuid:"+liveUuid);
    }
  }

	/**
	 * 给主播直播间加额外人数
	 */
	public String setAddNumForRoom(String userId, String number){
		String result = "";
		String key = String.format(GlobalConstants.AUTHOR_ADD_NUMBER, userId);
		try {
			result = jedisService.setexStr(key, number, GlobalConstants.AUTHOR_ADD_NUMBER_CACHE_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("{}加入额外人数失败",userId);
		}
		return result;
	}

	/**
	 * 获取主播直播间的额外人数
	 */
	public String getAddNumForRoom(String userId){
		String result = "";
		String key = String.format(GlobalConstants.AUTHOR_ADD_NUMBER, userId);
		try {
			result = jedisService.getStr(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取{}的额外人数失败",result);
		}
		return result;
	}

	/**
	 * 获取主播直播间所有真实人数
	 */
	@Override
	public long getLivingUserCountReal(String anchId){
		long result = 0l;
		try {
			Long robot = jedisService.llen(GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId);
			Long all = jedisService.zcard(GlobalConstants.LIVING_ROOM_USER_SORTED_KEY + anchId);
			if (null != all && null != robot) {
				result = all - robot;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("getLivingUserCountReal error :"+anchId);
		}
		return result;
	}

	/**
	 * 清除主播直播间所有真实人数的缓存
	 */
	@Override
	public void delLivingUserCountReal(String anchId){
		String key = String.format(GlobalConstants.AUTHOR_REAL_NUMBER, anchId);
		try {
			jedisService.del(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("delLivingUserCountReal error :"+anchId);
		}
	}

	/**
	 * 增加主播直播间所有真实人数
	 */
	@Override
	public long addLivingUserCountReal(String anchId, int num) {
		long result = 0l;
		try {
			String key = String.format(GlobalConstants.AUTHOR_REAL_NUMBER, anchId);
			result = jedisService.incrBy(key, num);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("addLivingUserCountReal  error", e);
		}
		return result;
	}

	/**
	 * 减少主播直播间所有真实人数
	 */
	@Override
	public long decLivingUserCountReal(String anchId, int num) {
		long result = 0l;
		try {
			String key = String.format(GlobalConstants.AUTHOR_REAL_NUMBER, anchId);
			result = jedisService.decrBy(key, num);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("decLivingUserCountReal  error", e);
		}
		return result;
	}

	/**
	 * IM发送策略检查
	 *
	 * @param authId：主播ID
	 * @param IMMsgType(0：小礼物 1：盒饭数 2：点亮 3：关注 4：弹幕 5：特效)
	 * @return
	 */
	@Override
	public boolean IMSendCheck(String authId, int IMMsgType) {
		try {
			Map<String, String> imConfigMap = liveConfigCenter.getImSendCheckConfig();
			int smsTypeConfig = MapUtils.getIntValue(imConfigMap, "isIMSendCheck", 0);
			logger.info("是否进行IM发送策略检查 smsTypeConfig=" + smsTypeConfig);
			if (smsTypeConfig == 1) {
				if (IMMsgType == 0) {//小礼物
					String key = String.format(GlobalConstants.IM_SEND_CHECK_LITTLE_PRESENT, authId);
					long num = jedisService.incrBy(key, 1);
					if (num == 1) {
						logger.info("小礼物IM发送策略初始化");
						jedisService.expire(key, 5);
					}
					int littlePresentMaxLimit = MapUtils.getIntValue(imConfigMap, "littlePresentMaxLimit", 0);
					if (littlePresentMaxLimit <= 0) {
						logger.info("ZK 小礼物IM发送最大限制数 配置错误");
						return true;
					}
					logger.info("小礼物IM发送最大限制数：" + littlePresentMaxLimit + " 当前数：" + num);
					if (num <= littlePresentMaxLimit) {
						logger.info("小礼物IM发送中");
					} else {
						logger.info("小礼物IM发送超过发送最大限制");
						return false;
					}
					return true;
				} else if (IMMsgType == 1) {//盒饭数
					String key = String.format(GlobalConstants.IM_SEND_CHECK_HEFAN_NUM, authId);
					long num = jedisService.incrBy(key, 1);
					if (num == 1) {
						logger.info("盒饭数IM发送策略初始化");
						jedisService.expire(key, 5);
					}
					int hefanNumMaxLimit = MapUtils.getIntValue(imConfigMap, "hefanNumMaxLimit", 0);
					if (hefanNumMaxLimit <= 0) {
						logger.info("ZK 盒饭数IM发送最大限制数 配置错误");
						return true;
					}
					logger.info("盒饭数IM发送最大限制数：" + hefanNumMaxLimit + " 当前数：" + num);
					if (num <= hefanNumMaxLimit) {
						logger.info("盒饭数IM发送中");
					} else {
						logger.info("盒饭数IM发送超出发送最大限制");
						return false;
					}
					return true;
				} else if (IMMsgType == 2) {//点亮
					String key = String.format(GlobalConstants.IM_SEND_CHECK_LIGHT, authId);
					long num = jedisService.incrBy(key, 1);
					if (num == 1) {
						logger.info("点亮IM发送策略初始化");
						jedisService.expire(key, 5);
					}
					int lightMaxLimit = MapUtils.getIntValue(imConfigMap, "lightMaxLimit", 0);
					if (lightMaxLimit <= 0) {
						logger.info("ZK 点亮IM发送最大限制数 配置错误");
						return true;
					}
					logger.info("点亮IM发送最大限制数：" + lightMaxLimit + " 当前数：" + num);
					if (num <= lightMaxLimit) {
						logger.info("点亮IM发送中");
					} else {
						logger.info("点亮IM发送超出最大发送限制");
						return false;
					}
					return true;
				} else if (IMMsgType == 3) {//关注
					String key = String.format(GlobalConstants.IM_SEND_CHECK_ATTENTION, authId);
					long num = jedisService.incrBy(key, 1);
					if (num == 1) {
						logger.info("关注IM发送策略初始化");
						jedisService.expire(key, 5);
					}
					int attentionMaxLimit = MapUtils.getIntValue(imConfigMap, "attentionMaxLimit", 0);
					if (attentionMaxLimit <= 0) {
						logger.info("ZK 关注IM发送最大限制数 配置错误");
						return true;
					}
					logger.info("关注IM发送最大限制数：" + attentionMaxLimit + " 当前数：" + num);
					if (num <= attentionMaxLimit) {
						logger.info("关注IM发送中");
					} else {
						logger.info("关注IM发送超出最大发送限制");
						return false;
					}
					return true;
				} else if (IMMsgType == 4) {//弹幕
					String key = String.format(GlobalConstants.IM_SEND_CHECK_BARRAGE, authId);
					long num = jedisService.incrBy(key, 1);
					if (num == 1) {
						logger.info("弹幕IM发送策略初始化");
						jedisService.expire(key, 5);
					}
					int barrageMaxLimit = MapUtils.getIntValue(imConfigMap, "barrageMaxLimit", 0);
					if (barrageMaxLimit <= 0) {
						logger.info("ZK 弹幕IM发送最大限制数 配置错误");
						return true;
					}
					logger.info("弹幕IM发送最大限制数：" + barrageMaxLimit + " 当前数：" + num);
					if (num <= barrageMaxLimit) {
						logger.info("弹幕IM发送中");
					} else {
						logger.info("弹幕IM发送超出最大发送限制");
						return false;
					}
					return true;
				} else if (IMMsgType == 5) {//特效
					String key = String.format(GlobalConstants.IM_SEND_CHECK_SPECIAL_EFFICIENCY, authId);
					long num = jedisService.incrBy(key, 1);
					if (num == 1) {
						logger.info("特效IM发送策略初始化");
						jedisService.expire(key, 5);
					}
					int specialEfficiencyMaxLimit = MapUtils.getIntValue(imConfigMap, "specialEfficiencyMaxLimit", 0);
					if (specialEfficiencyMaxLimit <= 0) {
						logger.info("ZK 特效IM发送最大限制数 配置错误");
						return true;
					}
					logger.info("特效IM发送最大限制数：" + specialEfficiencyMaxLimit + " 当前数：" + num);
					if (num <= specialEfficiencyMaxLimit) {
						logger.info("特效IM发送中");
					} else {
						logger.info("特效IM发送超出最大发送限制");
						return false;
					}
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("IM发送策略检查异常");
		}
		return true;
	}

	/**
	 * 全部机器人缓存中删除机器人信息
	 * @param userId
	 * @return
     */
	@Override
	public long removeRobotInAll(String userId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROBOT_HASHSET_KEY;
			jedisService.hdel(key, userId);
			key = GlobalConstants.LIVING_ROBOT_LIST_KEY;
			result = jedisService.lrem(key, -1, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("IMSendCheck  error", e);
		}
		return result;
	}

	/**
	 * 直播间机器人缓存中删除机器人信息
	 * @param userId
	 * @return
	 */
	@Override
	public long removeRobotInRoom(String userId, String anchId) {
		long result = 0l;
		try {
			String key = GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId;
			result = jedisService.lrem(key, -1, userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("removeRobotInRoom  error", e);
		}
		return result;
	}

	/**
	 * 直播间踢机器人
	 */
	@Override
	public void outRobot(String anchId,String userId) {
		try {
			String keyRoom = GlobalConstants.LIVING_ROOM_ROBOT_LIST_KEY + anchId;
			Long l = jedisService.lrem(keyRoom, 0, userId);
			if (null != l) {
				logger.info("直播间内清除机器人：{}，行数：{}", userId, l);
			}
			String keyAll = GlobalConstants.LIVING_ROBOT_LIST_KEY;
			l = jedisService.lrem(keyAll, 0, userId);
			if (null != l) {
				logger.info("防重，全部机器人缓存中清除{}行数{}",userId, l);
			}
			l =jedisService.rpush(keyAll, userId);
			if (null != l) {
				logger.info("机器人{}被踢出后，归还全局行数{}", userId, l);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
